package com.mxm.mirai.web;


import com.mxm.mirai.jwt.JWTUtil;
import com.mxm.mirai.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.Charset;
import java.util.Base64;

@Api(value = "主页")
@Controller
public class IndexWeb {

    @Autowired
    UserService userService;

    @Value("classpath:templates/json/admin.json")
    private Resource admininit;
    @Value("classpath:templates/json/user.json")
    private Resource userinit;

    @RequestMapping({"/","index"})
    public String Index(){
        return "index";
    }
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/admin")
    public String admin(){
        return "admin";
    }
    @RequestMapping("/admin_init")
    @RequiresRoles(logical = Logical.OR, value = {"user", "admin"})//角色
    @ApiOperation(value = "用户/管理员 后台访问", notes = "拥有 user, admin 角色的用户可以访问下面的页面")
    public String admininit(){
        return "admin_init";
    }
    @ResponseBody
    @GetMapping("/init")
    public String admin_init(String token){
       try {
           String name = JWTUtil.getUsername(new String(Base64.getDecoder().decode(token), "UTF-8"));
           System.out.println(name);
           String role = userService.getRole(name);//获得该用户角色
           if ("admin".equals(role)) {
               return IOUtils.toString(admininit.getInputStream(), Charset.forName("UTF-8"));
           } else {
               return IOUtils.toString(userinit.getInputStream(), Charset.forName("UTF-8"));
           }
       }catch (Exception e){
           return null;
       }
    }
}
